package com.fc.mall.kdniao.util;

import com.fc.mall.kdniao.exception.KDNiaoErrorCode;
import com.fc.mall.kdniao.exception.KDNiaoException;
import org.apache.commons.codec.Charsets;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

public class KDNiaoHttpClientUtils {

    private static volatile KDNiaoHttpClientUtils instance = null;

    private PoolingHttpClientConnectionManager connectionManager;

    private CloseableHttpClient httpClient;

    private KDNiaoHttpClientUtils() {
        connectionManager = new PoolingHttpClientConnectionManager();
        // Increase max total connection to 500
        connectionManager.setMaxTotal(500);
        // Increase default max connection per route to 20
        connectionManager.setDefaultMaxPerRoute(20);

        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(10000)
                .setSocketTimeout(10000)
                .build();

        httpClient = HttpClients.custom().setConnectionManager(connectionManager)
                .setDefaultRequestConfig(requestConfig)
                .build();
    }

    public static KDNiaoHttpClientUtils getInstance() {
        if (instance == null) {
            synchronized (KDNiaoHttpClientUtils.class) {
                if (instance == null) {
                    instance = new KDNiaoHttpClientUtils();
                }
            }
        }
        return instance;
    }


    /**
     * 发送POST请求
     * @param url
     * @param params
     * @param contentType
     * @return
     */
    public String sendPost(String url, String params, String contentType) {
        HttpPost httpPost = new HttpPost(url);// 创建httpPost
        httpPost.setHeader("Accept", "*/*");
        httpPost.setHeader("Content-Type", contentType);

        StringEntity entity = new StringEntity(params, Charsets.UTF_8);
        httpPost.setEntity(entity);
        String responseStr;
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpPost);
            StatusLine status = response.getStatusLine();
            int state = status.getStatusCode();
            if (state == HttpStatus.SC_OK) {
                HttpEntity responseEntity = response.getEntity();
                responseStr = EntityUtils.toString(responseEntity);
            } else{
                throw new KDNiaoException(KDNiaoErrorCode.HTTP_RESPONSE_STATUS_ERROR, String.valueOf(state));
            }
        } catch (Exception ex) {
            throw new KDNiaoException(KDNiaoErrorCode.HTTP_CONNECTION_ERROR, ex.getMessage());
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException ex) {
                    throw new KDNiaoException(KDNiaoErrorCode.HTTP_CONNECTION_ERROR, ex.getMessage());
                }
            }

            if (httpPost != null) {
                httpPost.abort();
                httpPost.releaseConnection();
            }
        }
        return responseStr;
    }
}
